import {Component, EventEmitter, Input, OnChanges, OnInit, Output, SimpleChanges} from '@angular/core';
import {NzUploadFile, NzUploadXHRArgs} from "ng-zorro-antd/upload";
import {HttpClient, HttpEvent, HttpEventType, HttpRequest, HttpResponse} from "@angular/common/http";
import {AttachmentService} from "../../services/util/attachment.service";
import {AuthService} from "../../services/auth.service";
import {ConfigService} from "../../services/config.service";

@Component({
    selector: 'app-picture-upload',
    templateUrl: './picture-upload.component.html',
    styleUrls: ['./picture-upload.component.scss']
})
export class PictureUploadComponent implements OnInit, OnChanges {
    @Input() public editable: boolean = false; //是否可以编辑
    @Input() public pictures: any = []; //传进来的照片列表
    @Input() public amount: Number = 999; //最大图片数
    @Output() onChange = new EventEmitter();

    url: string = this.configService.api.upload_api; //图片上传地址,这个地址是否改成可配置的需讨论一下，因为与relative path配套使用
    picture_list: any = []; //控件内界面绑定的照片列表
    preview_image: string = "";
    preview_visible: boolean = false;

    constructor(private http: HttpClient, private authService: AuthService, private configService: ConfigService, private attachmentService: AttachmentService) {
    }

    ngOnInit() {
    }

    ngOnChanges(changes: SimpleChanges) {
        if (changes.pictures && changes.pictures.currentValue) {
            this._init();
        }

        if (changes.editable && changes.editable.previousValue !== changes.editable.currentValue) {
            this._init();
        }
    }

    /////////////////以下私有函数/////////////////////
    _init() {
        if(Array.isArray(this.pictures)){
            this.picture_list = this.pictures.map((p) => {
                return {
                    uid: p._id,
                    name: p.auto_name,
                    url: this.configService.api.download_api + "/" +  p.auto_name
                }
            });
        }else{
            this.picture_list = [];
        }
    }


    /////////////////以下界面交互/////////////////////
    //图片上传
    customReq = (item: NzUploadXHRArgs) => {
        const new_attachments = [];
        const formData = new FormData();
        formData.append('file', item.file as any, item.file.name);
        const req = new HttpRequest('POST', item.action, formData, {
            reportProgress: true,
        });

        return this.http.request(req).subscribe((event: HttpEvent<any>) => {
            if (event.type === HttpEventType.UploadProgress) {
                if (event.total > 0) {
                    (event as any).percent = event.loaded / event.total * 100;
                }// 处理上传进度条
                item.onProgress(event, item.file);
            } else if (event instanceof HttpResponse) {
                // 处理成功
                item.onSuccess(event.body, item.file, event);
                if (event.body) {
                    event.body.paths.forEach((path, index) => {
                        const attachment = {
                            origin_name: path.original_name,
                            date: new Date(),
                            auto_name: path.auto_name,
                            file_type: path.file_type,
                            file_size: '0KB'
                        };
                        if (item.file.size / 1024 < 1024) {
                            attachment.file_size = (item.file.size / 1024).toFixed(1) + "KB";
                        } else if (item.file.size / (1024 * 1024) < 1024) {
                            attachment.file_size = (item.file.size / (1024 * 1024)).toFixed(1) + "MB";
                        } else {
                            attachment.file_size = (item.file.size / (1024 * 1024 * 1024)).toFixed(1) + "GB";
                        }
                        new_attachments.push(attachment);
                    });
                    this.attachmentService.createMany(new_attachments).subscribe(res => {
                        if(res.result){
                            res.docs.forEach(attachment => {
                                this.pictures.push(attachment);
                            });
                            this.onChange.emit(this.pictures);
                        }
                    });
                }
            }
        }, (err) => {
            // 处理失败
            item.onError(err, item.file);
        });
    };

    //图片删除
    deletePic = (file: NzUploadFile) => {
        const index1 = this.pictures.findIndex(item => item._id === file.uid);
        index1 >= 0 && this.pictures.splice(index1,1);
        //const index2 = this.picture_list.findIndex(item => item.name === file.name);
        //index2 >= 0 && this.picture_list.splice(index2,1);
        this.onChange.emit(this.pictures);
        return true;
    };

    //图片放大预览
    handlePreview = (file: NzUploadFile) => {
        this.preview_image = file.url || file.thumbUrl;
        this.preview_visible = true;
    };
}
